<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="896" @ok="handleSubmit">
    <BasicForm @register="registerForm" ref="formref">
      <template #cardNumberSlot1="{ model, field }">
        <a-input v-model:value="model[field]" type="Input"  @blur="addZero"  required placeholder="请输入卡号!" />
        <a-button @click="readCard">读卡</a-button><!--&nbsp;&nbsp;&nbsp;&nbsp;
        <a-button @click="addZero">补零</a-button>-->
      </template>
    </BasicForm>
  </BasicModal>
</template>

<script lang="ts" setup>
  import {ref, computed, unref} from 'vue';
  import {BasicModal, useModalInner} from '/@/components/Modal';
  import {BasicForm, FormSchema, useForm} from '/@/components/Form/index';
  import {recard, saveOrUpdate} from '../SsCard.api';
  import {list} from "@/views/baseinfo/person/SsPerson.api";
  import {useMessage} from "@/hooks/web/useMessage";
  // Emits声明
  const emit = defineEmits(['register','success']);
  const isUpdate = ref(true);
  const formref = ref({});
  const { createMessage } = useMessage();
  const formSchema: FormSchema[] = [
    {
      label: '卡号',
      field: 'cardNumber',
      component: 'Input',
      dynamicDisabled:true,
    },
    {
      label: '新卡号',
      field: 'reCardNumber',
      component: 'Input',
      dynamicRules: ({ values }) => {
      console.log('values:', values);
      //需要return
      return [
        {
          //默认开启表单检验
          required: true,
          // value 当前卡号输入的值
          validator: (_, value) => {
            //需要return 一个Promise对象
            return new Promise((resolve, reject) => {
              if (!value) {
                reject('请输入卡号！');
              }
              //验证卡号是否正确
              let reg = /^[a-zA-Z0-9]{10}$/;
              if (!reg.test(value)) {
                reject('请输入10位字母或者数字卡号！');
              }
              resolve();
            });
          },
        },
      ];
    },
      slot:"cardNumberSlot1",
    },
    {
      label: '手续费',
      field: 'saleCard',
      component: 'Input',
      defaultValue: 25
    },
    
    ];
  //表单配置
  const [registerForm, {getForm,setProps,resetFields, setFieldsValue, getFieldsValue,validate,updateSchema}] = useForm({
    labelWidth: 150,
    schemas: formSchema,
    showActionButtonGroup: false,
    baseColProps: {span: 24}
  });
  let closePm = undefined;
  //表单赋值
  const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
    //重置表单
    await resetFields();
    setModalProps({confirmLoading: false,showCancelBtn:!!data?.showFooter,showOkBtn:!!data?.showFooter});
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      data.record.saleCard=25
      //表单赋值
      await setFieldsValue({
        ...data.record,
      });
      closePm = data?.closePm;
    }
    // 隐藏底部时禁用整个表单
    setProps({ disabled: !data?.showFooter })
  });
  //设置标题
  const title = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));


  function addZero(){
    let cn = getFieldsValue().reCardNumber;
    let cn1 = addZeroExt(cn);
    setFieldsValue({reCardNumber:cn1});
  }
  function addZeroExt(cn){
    let len = cn.length;
    for(let i = 0;i<10-len;i++){
      cn = "0"+cn;
    }
    return  cn ;
  }


  //根据卡号查询会员信息
  function readCard() {

    // （1） 获取 XMLHttpRequest对象
    let xmlHttp = new XMLHttpRequest();

    //  post
    xmlHttp.open("post","http://127.0.0.1:19999/dllinterface");

    // 设置请求头的Content-Type
    xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");

    // （3） 发送数据
    // （4） 回调函数  success
    xmlHttp.onreadystatechange = function() {
      console.log(this);
      console.log(this.readyState);
      console.log(this.status);
      if(this.readyState==4 && this.status==200){
        console.log(this.responseText)
        var respHead = this.responseText.substring(0, 5);
        var respMsg = this.responseText.substring(5);
        console.log(respHead);
        console.log(respMsg);
        if ("EROR-" == respHead) {
          createMessage.error('提示:'+respMsg);
          return false;
        } else if ("SUCC-" == respHead) {
          console.log("卡号=" + respMsg);
          let cn1 = addZeroExt(respMsg);
          setFieldsValue({reCardNumber:cn1});
          return true;
        } else {
          createMessage.warn('提示:'+this.responseText);
          return false;
        }
      }
    };

    xmlHttp.send('JBDL') ;   // 请求体数据

  }

  //表单提交事件
  async function handleSubmit(v) {
    try {
      let values = await validate();
      setModalProps({confirmLoading: true});
      //提交表单
      await recard(values, isUpdate.value);
      //关闭弹窗
      closeModal();
      if(closePm){
        closePm();
      }
      //刷新列表
      emit('success');
    } finally {
      setModalProps({confirmLoading: false});
    }
  }
</script>

<style lang="less" scoped>
  /** 时间和数字输入框样式 */
  :deep(.ant-input-number){
    width: 100%
  }

  :deep(.ant-calendar-picker){
    width: 100%
  }
</style>
